package com.iot.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.iot.core.domain.BaseDO;
import com.iot.core.domain.PageSO;

import java.io.Serializable;

public class PageUtils implements Serializable {

	/**
	 * 根据对象构建查询实体对象
	 * @param pageSO
	 * @param entity
	 * @param <T>
	 * @return
	 */
	public static <T extends BaseDO> T buildSearchPage(PageSO pageSO,T entity) {
		entity.setPageSO(pageSO);
		BeanUtils.copyJSONToObject(pageSO.getParams(),entity);
		return entity;
	}

	/**
	 * 根据类名构建查询实体对象
	 * @param pageSO
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T extends BaseDO> T buildSearchPage(PageSO pageSO,Class<T> clazz) {
		try {
			T entity = clazz.newInstance();
			BeanUtils.copyJSONToObject(pageSO.getParams(),entity);
			entity.setPageSO(pageSO);
			return entity;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 根据类名构建查询实体对象
	 * @param pageSO
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T extends BaseDO> T buildSearchPage(JSONObject pageSO, Class<T> clazz) {
		try {
			T entity = clazz.newInstance();
			PageSO page = new PageSO();
			if (null != pageSO) {
				if (pageSO.getIntValue("page") != 0) {
					page.setPage(pageSO.getIntValue("page"));
				}
				if (pageSO.getIntValue("limit") != 0) {
					page.setLimit(pageSO.getIntValue("limit"));
				}
				page.setSort(pageSO.getString("sort"));
				JSONObject params = pageSO.getJSONObject("params");
				if (null != params) {
					BeanUtils.copyJSONToObject(params,entity);
					page.setParams(params);
				}
			}
			entity.setPageSO(page);
			return entity;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
}
